<template>
	<view>
		<view class="header">
			<view id="back" v-if="back">
				<u-icon name="arrow-left" @click="clickBack" size="60rpx"></u-icon>
			</view>
			<text id="title">应用设置</text>
		</view>
		<u-cell-group>
			<u-cell title="消息推送" size="large">
				<view slot="right-icon">
					<u-switch size="42" v-model="pushEnabled" activeColor="#3d5cff" @change="changePush"></u-switch>
				</view>
			</u-cell>
			<u-cell title="缓存清理" :value="cacheSize" size="large" @click="clearCache">
				<view slot="right-icon" v-if="calculating">
					<u-loading-icon size="42" mode="circle"></u-loading-icon>
				</view>
			</u-cell>
		</u-cell-group>
	</view>
</template>

<script>
	var _this = null;
	const message = require('message.js');
	export default {
		data() {
			return {
				back: false,
				pushEnabled: true,
				calculating: true,
				cacheSize: ''
			}
		},
		methods: {
			clickBack: function(e) {
				var pages = getCurrentPages();
				if (pages.length > 1) {
					uni.navigateBack({
						url: pages[pages.length - 2].url
					})
				}
			},
			changePush: function(e) {
				uni.setStorageSync('pushMessage', e);
				message.setPushEnabled(e);
			},
			loadCacheInfo: function() {
				uni.getStorageInfo({
					success: function (res) {
						_this.calculating = false;
						_this.cacheSize = res.currentSize + 'KB';
					}
				});
			},
			clearCache: function() {
				if (_this.calculating) {
					return;
				}
				_this.calculating = true;
				_this.cacheSize = '';
				uni.showLoading({
					title: '清理中',
					mask: true
				})
				setTimeout(() => {
					uni.hideLoading();
					uni.clearStorage();
					_this.loadCacheInfo();
					uni.setStorage({
						key: 'pushMessage',
						data: _this.pushEnabled
					});
					api.saveToken();
				}, 1000);
			}
		},
		onLoad() {
			_this = this;
			_this.back = getCurrentPages().length > 1;
			_this.loadCacheInfo();
			_this.pushEnabled = message.isPushEnabled();
		}
	}
</script>

<style lang="scss" scoped>
	.header {
		height: calc(var(--status-bar-height) + 96rpx);
		position: relative;
	
		#back {
			position: absolute;
			padding-top: calc(var(--status-bar-height) + 18rpx);
			padding-left: 12rpx;
			z-index: 99;
		}
	
		#title {
			position: absolute;
			left: 320rpx;
			top: calc(var(--status-bar-height) + 22rpx);
			font-weight: 1000;
			font-family: 'YouYuan';
			font-size: 36rpx;
		}
	}
</style>
